<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="searchCompany">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/park/add')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <!-- expand-change 事件：展开行时，触发该事件 -->
      <el-table style="width: 100%" :data="companyList" @expand-change="handleExpandChange">
        <!-- 表格的展开行方法 -->
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态">
                <template #default="scope">
                  <!-- 利用了格式化tag的方法，将数据转化为对应的中文内容 -->
                  <el-tag :type="formatStatus(scope.row.status)">
                    {{ formatStatus(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <!-- 已到期的房租，禁止操作退租和删除，直接通过上一级删除 -->
                  <el-button size="mini" type="text" :disabled="scope.row.status === 3" @click="outRent(scope.row.id)">退租</el-button>
                  <el-button size="mini" type="text" :disabled="scope.row.status === 3" @click="deleteContract(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button size="mini" type="text" @click="addContract(row.id)">添加合同</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/park/enterprise/detail/${row.id}`)">查看</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/park/add/${row.id}`)">编辑</el-button>
            <el-popconfirm
              title="确定要永久删除该数据吗？"
              @confirm="del(row.id)"
            >
              <el-button
                slot="reference"
                :disabled="row.existContractFlag === 1"
                style="margin-left: 10px;"
                size="mini"
                type="text"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        :current-page.sync="params.page"
        @current-change="handlePageChange"
      />
    </div>
    <!-- 添加合同弹层 -->
    <el-dialog title="添加合同" :visible="isShowAddContract" width="580px" @close="close">
      <el-form ref="formRef" label-position="top" :model="form" :rules="rules" label-width="100px" class="form-container">
        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select v-model="form.buildingId" placeholder="请选择租赁的楼宇">
            <el-option v-for="item in buildingList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="租赁起止日期" prop="contractTime">
          <el-date-picker
            v-model="form.contractTime"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="租赁合同" prop="contractId">
          <el-upload
            action="#"
            :http-request="uploadRequest"
            :before-upload="beforeUpload"
          >
            <el-button size="small" type="primary">点击上传合同</el-button>
            <div slot="tip" class="el-upload__tip">支持扩展名: .doc .docx .pdf, 文件大小不得超过5M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addContractAPI, deleteCompanyAPI, deleteContractAPI, getBuildingListAPI, getCompanyListAPI, getContractListAPI, outRentAPI, uploadContractAPI } from '@/api/park'

export default {
  data() {
    return {
      companyList: [],
      params: {
        page: 1,
        pageSize: 5,
        name: ''
      },
      total: 0,
      isShowAddContract: false,
      form: {
        buildingId: null, // 楼宇id
        contractTime: [], // 合同时间数组
        type: 0, // 类型
        enterpriseId: null, // 企业id
        contractId: null, // 合同id
        contractUrl: '' // 合同url
      },
      rules: {
        contractId: [
          { required: true, message: '请上传合同' }
        ],
        buildingId: [
          { required: true, message: '请选择租赁楼宇', trigger: 'change' }
        ],
        contractTime: [
          { required: true, message: '请选择租赁起止日期', trigger: 'change' }
        ]
      },
      buildingList: []
    }
  },
  created() {
    this.getCompanyList()
    this.getBuildingList()
  },
  methods: {
    // 获取楼宇列表
    async getBuildingList() {
      const res = await getBuildingListAPI()
      // console.log(res)
      this.buildingList = res.data.rows
    },
    // 获取企业列表
    // 初始化时增加合同数据默认列表
    async getCompanyList() {
      const res = await getCompanyListAPI(this.params)
      // console.log(res)
      this.companyList = res.data.rows.map(item => {
        return {
          ...item,
          rentList: [] // 每一行补充存放合同的数据
        }
      })
      this.total = res.data.total
    },
    // 切换页码
    handlePageChange(page) {
      this.params.page = page
      this.getCompanyList()
    },
    // 根据名字查询企业
    async searchCompany() {
      this.params.page = 1
      await this.getCompanyList()
      if (this.companyList.length === 0) {
        this.$message.error('没有该企业')
      } else {
        this.$message.success('查询成功')
      }
    },
    // 删除功能
    async del(id) {
      await deleteCompanyAPI(id)
      this.$message.success('删除成功')
      // 如果删除的是最后一个数据，页码减1
      if (this.params.page > 1 && this.companyList.length === 1) {
        this.params.page--
      }
      this.getCompanyList()
    },
    // 添加合同按钮
    addContract(id) {
      this.isShowAddContract = true
      this.form.enterpriseId = id
    },
    // 关闭弹层
    close() {
      this.isShowAddContract = false
      this.$refs.formRef.resetFields()
    },
    // 确认添加合同
    async confirmAdd() {
      await this.$refs.formRef.validate()
      // console.log('成功')
      this.form.startTime = this.form.contractTime[0]
      this.form.endTime = this.form.contractTime[1]
      delete this.form.contractTime
      // console.log(this.form)
      await addContractAPI(this.form)
      this.$message.success('合同添加成功')
      this.getCompanyList()
      this.close()
    },
    // 上传文件前
    beforeUpload(file) {
      // 判断合同文件类型是否为.pdf .doc .docx
      const allowImgType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!allowImgType) {
        this.$message.error('上传文件只能是 PDF、DOC、DOCX 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 上传文件
    async uploadRequest(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('type', 'contract')
      const res = await uploadContractAPI(formData)
      // console.log(res)
      this.form.contractId = res.data.id
      this.form.contractUrl = res.data.url
      // 上传完成后校验一下
      // console.log(this.form)
      this.$refs.formRef.validateField('contractId')
    },
    // 展开详情
    async handleExpandChange(row, expandedRows) {
      // console.log('展开列表', row, expandedRows)
      // 判断是否展开
      // expandedRows为展开的行的所有数据
      // row为展开后的行数据
      const isExpand = expandedRows.find(item => item.id === row.id)
      if (isExpand) {
        const res = await getContractListAPI(row.id)
        // console.log(res)
        // eslint-disable-next-line require-atomic-updates
        row.rentList = res.data
        // this.$set(row, 'rentList', res.data)
      }
    },
    // 格式化tag类型
    formatInfoType(status) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      // 返回格式化之后的中文显示
      return MAP[status]
    },
    // 格式化status
    formatStatus(type) {
      const TYPEMAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return TYPEMAP[type]
    },
    // 退租
    async outRent(id) {
      await this.$confirm('确认退租吗?')
      await outRentAPI(id)
      this.getCompanyList()
      this.$message.success('退租成功')
    },
    // 删除租赁合同
    async deleteContract(id) {
      await this.$confirm('确认删除该合同吗?')
      await deleteContractAPI(id)
      this.$message.success('删除成功')
      this.getCompanyList()
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>

